//
//  WYWDownLoaderManager.m
//  WYWDownloader
//
//  Created by Mr.Run on 2017/11/8.
//  Copyright © 2017年 Mr.Run. All rights reserved.
//

#import "WYWDownLoaderManager.h"
#import "NSString+Extension.h"

@interface WYWDownLoaderManager ()<NSCopying, NSMutableCopying>

@property (nonatomic,strong) NSMutableDictionary *downLoaderInfo;

@end

@implementation WYWDownLoaderManager

static WYWDownLoaderManager *_shareInstance;
+(instancetype)shareInstance{
    if (_shareInstance == nil) {
        _shareInstance = [[self alloc]init];
    }
    return _shareInstance;
}

+(instancetype)allocWithZone:(struct _NSZone *)zone{
    
    if (!_shareInstance) {
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            _shareInstance = [super allocWithZone:zone];
        });
    }
    return _shareInstance;
}

-(id)copyWithZone:(NSZone *)zone{
    return _shareInstance;
}

-(id)mutableCopyWithZone:(NSZone *)zone{
    return _shareInstance;
}

- (NSMutableDictionary *)downLoaderInfo{
    if (!_downLoaderInfo) {
        _downLoaderInfo = [NSMutableDictionary dictionary];
    }
    return _downLoaderInfo;
}

-(void)downLoader:(NSURL *)url downLoadInfo:(DownLoadInfoType)downLoadInfo progress:(ProgressBlockType)progress success:(SuccessBlockType)success failed:(FailedBlockType)failed{
    
    NSString *urlMD5 = [url.absoluteString md5];
    
    WYWDownLoader *downLoader = self.downLoaderInfo[urlMD5];
    
    if (downLoader == nil) {
        downLoader = [[WYWDownLoader alloc]init];
        self.downLoaderInfo[urlMD5] = downLoader;
    }
    
//    [downLoader downLoader:url downLoadInfo:downLoadInfo progress:progress success:success failed:failed];
    [downLoader downLoader:url downLoadInfo:downLoadInfo progress:progress success:^(NSString *cachePath) {
        [self.downLoaderInfo removeObjectForKey:urlMD5];
        success(cachePath);
    } failed:failed];
}

-(void)pauseWithURL:(NSURL *)url{
    NSString *urlMD5 = [url.absoluteString md5];
    WYWDownLoader *downLoader = self.downLoaderInfo[urlMD5];
    [downLoader pauseCurrentTask];
}

-(void)resumeWithURL:(NSURL *)url{
    NSString *urlMD5 = [url.absoluteString md5];
    WYWDownLoader *downLoader = self.downLoaderInfo[urlMD5];
    [downLoader resumeCurrentTask];
}

-(void)cancelWithURL:(NSURL *)url{
    NSString *urlMD5 = [url.absoluteString md5];
    WYWDownLoader *downLoader = self.downLoaderInfo[urlMD5];
    [downLoader cancelCurrentTask];
}
    
-(void)pauseAll{
    [self.downLoaderInfo.allValues performSelector:@selector(pauseCurrentTask) withObject:nil];
}

-(void)resumeAll{
    [self.downLoaderInfo.allValues performSelector:@selector(resumeCurrentTask) withObject:nil];
}

@end
